package com.example.demo.controller;

import com.example.demo.commen.AppResult;
import com.example.demo.commen.ResultCode;
import com.example.demo.exception.ApplicationException;
import com.example.demo.model.Article;
import com.example.demo.model.Board;
import com.example.demo.model.User;
import com.example.demo.service.impl.ArticleServiceImpl;
import com.example.demo.service.impl.BoardServiceImpl;
import com.example.demo.service.impl.UserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RequestMapping("/article")
@RestController
@Slf4j
@Api(tags = "帖子接口")
public class ArticleController {

    @Autowired
    private ArticleServiceImpl articleService;

    @Autowired
    private BoardServiceImpl boardService;

    @Autowired
    private UserServiceImpl userService;

    @RequestMapping(method = RequestMethod.POST,value = "/release")
    @ApiOperation("发帖子")
    public AppResult releaseArticle(HttpServletRequest request,
                                    @ApiParam("版块ID")@RequestParam("boardId")int boardId,
                                    @ApiParam("标题")@RequestParam("title")String title,
                                    @ApiParam("正文")@RequestParam("content")String content){
        HttpSession session = request.getSession(false);    //这里的session其实可以省略了，因为我们实现了登录拦截器，能进这个页面
                                                               //说明已经登录了
        User user = (User) session.getAttribute("userInfo");
        if(user==null){
            log.info("发帖--用户不存在");
            throw new ApplicationException("用户不存在");
        }
        if(user.getState()==1){           //用户被禁言了 ，，这里是必要的，所以还是得通过session获取一下用户
            return AppResult.failed(ResultCode.FAILED_USER_BANNED.getMessage());
        }

      if(boardId<=0||title==null||
          !StringUtils.hasLength(title)||!StringUtils.hasLength(content)){
          log.info("发帖子参数有错误");
          throw  new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
      }
        Board board = boardService.selectById(Long.valueOf(boardId));
      if(board==null||board.getDeleteState()==1){
          throw  new ApplicationException("版块不存在");
      }

      Article article = new Article();
      article.setBoardId(board.getId());   //也可以直接使用前端传入的参数blogId,这个一样的
      article.setContent(content);
      article.setTitle(title);
      article.setUserId(user.getId());    //当前用户
        System.out.println(article);
        articleService.insertArticle(article);
        log.info("发帖成功");
        return AppResult.success("发帖成功");
    }

    @ApiOperation("获取对应版块帖子列表")
    @RequestMapping(method = RequestMethod.GET,value = "/getAllArticleByBoardId")
    public AppResult<List<Article>> getAllArticle(@ApiParam("首页")
                                                    @RequestParam(value = "boardId",required = false)
                                                       Long boardId){

        List<Article> lists = new ArrayList<>();

        if(boardId==null) {
           lists = articleService.selectAll();
            if (lists == null) {
                lists = new ArrayList<>();
            }
        }
        else{
            Board board = boardService.selectById(boardId);
            if(board==null){
                throw  new ApplicationException("版块不存在-显示不了");
            }
            lists = articleService.selectMatchAllByBoardId(boardId);
            if(lists==null){
                lists = new ArrayList<>();
            }
        }
        return AppResult.success(lists);
    }


    @ApiOperation("对应版块的名称和帖子数量")
    @RequestMapping(method = RequestMethod.GET,value = "/board")

    public AppResult<Board> getBoardById(@ApiParam("版块ID")
                                         @RequestParam(value = "boardId",required = true) Long boardId ){
              if(boardId==null||boardId<=0){
                  throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
              }
       Board board = articleService.selectBoardById(boardId);
              if(board==null||board.getDeleteState()==1){
                  throw  new ApplicationException(ResultCode.FAILED.toString());
              }
            return AppResult.success(board);
    }

   @ApiOperation("帖子详情")
   @RequestMapping(method = RequestMethod.GET,value = "/articleDetail")
    public AppResult<Article> getArticleDetail(@ApiParam("帖子Id")
                                              HttpServletRequest request, @RequestParam(value = "articleId",required = true) Long articleId){

        HttpSession session = request.getSession(false);   //这里无需判断是否登录了，因为拦截器帮我们做了

       User user = (User) session.getAttribute("userInfo");

        if(articleId==null||articleId<=0){
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
       Article article = articleService. selectDetailByArticleId(articleId);
        if(article==null){
            throw new ApplicationException("该帖子详情查询失败--请联系管理员");
        }

       if(user.getId()==article.getUserId()){
           article.setOwn(true);
       }
        return AppResult.success(article);
   }

   @ApiOperation("帖子编辑")
    @RequestMapping(method = RequestMethod.POST,value = "/articleEditor")
    public AppResult editorArticle(HttpServletRequest request,
                                   @ApiParam("帖子的Id") Long id,
                                   @ApiParam("帖子标题") String title,
                                   @ApiParam("帖子正文")String content){

       HttpSession session = request.getSession(false);
       User user = (User) session.getAttribute("userInfo");

       if(user.getState()==1) {            //如果为1则被禁言了
         throw  new ApplicationException(ResultCode. FAILED_USER_BANNED.toString());
       }
        if(id==null||id<=0||title==null||!StringUtils.hasLength(title)||!StringUtils.hasLength(content)||content==null){
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        //判断是不是本帖子的作者

        Article newArticle = articleService.selectDetailByArticleId(id);
        if(user.getId()!=newArticle.getUserId()){
            throw new ApplicationException("不是帖子的作者-不可编辑");
        }
        if(newArticle==null||newArticle.getId()<=0){
            throw new ApplicationException("帖子不存在");
        }

        if(newArticle.getState()==1) {          //此帖子作者设置为不可编辑
            throw new ApplicationException("此帖子作者设置为不可编辑了");
        }
        newArticle.setTitle(title);
        newArticle.setContent(content);
       Date date = new Date();
        newArticle.setUpdateTime(date);
        articleService.updateArticleDetail(newArticle);
        return AppResult.success();
   }


   @ApiOperation("帖子点赞")
    @RequestMapping(method = RequestMethod.POST,value = "/admiration")
    public AppResult articleAdmiration(@ApiParam("帖子ID")@RequestParam("id") @NonNull Long id){
        if(id==null||id<=0){
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        Article article = articleService.selectDetailByArticleId(id);
        if(article==null||article.getId()<=0){
            throw new ApplicationException("帖子不存在");
        }

        article = articleService.updateArticleAdmiration(id);
        if(article==null||article.getId()<=0){
            throw new ApplicationException("帖子不存在");
        }
        return AppResult.success();

   }

   @ApiOperation("删除帖子")
    @RequestMapping(method = RequestMethod.POST,value = "/deleteArticle")

    public AppResult deleteArticleById(HttpServletRequest request,
                                       @ApiParam("帖子ID")@RequestParam("id") Long id){
       if(id==null||id<=0){
           throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
       }
       HttpSession session = request.getSession(false);
       User user = (User) session.getAttribute("userInfo");
       Article article = articleService.selectArticleById(id);
       if(article==null||article.getId()<=0||article.getDeleteState()==1){
           throw new ApplicationException("帖子不存在");
       }
       if(user.getId()!=article.getUserId()){
           throw  new ApplicationException(ResultCode.FAILED_UNAUTHORIZED.toString());
       }

       articleService.deleteArticleById(article.getId());
       return AppResult.success("删除成功");

   }

   @ApiOperation("根据用户ID查询帖子(我的)")
  @RequestMapping(method = RequestMethod.GET,value = "/userArticle")

    public AppResult<List<Article>> getArticleByUserId(HttpServletRequest request, @ApiParam("用户Id")@RequestParam(value = "userId",required = false) Long userId){

        if(userId==null){         //代表查询的是当前用户

            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute("userInfo");
            if(user==null||user.getId()<=0){
                throw new ApplicationException("用户不存在");
            }
            userId = user.getId();
        }
        List<Article> list = articleService.selectArticleByUserId(userId);

        return AppResult.success(list);
   }

}
